<template>
  <div class="followup-box inner-content">


    <div class="inner inner-content-box">
      <div class="searchBox">
        <el-form
          :inline="true"
          :model="searchForm"
          size="small"
          style="width: 100%"
        >
          <el-form-item label="科室名称">
            <el-input v-model="searchForm.deptName" placeholder="科室名称" clearable style='width: 160px;'></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="getList"
              size="small"
              icon="el-icon-search"
              >搜索</el-button
            >
            <el-button @click="searchReset" size="small" icon="el-icon-delete"
              >清空</el-button
            >
          </el-form-item>
          <br />
          <el-form-item>
            <el-button v-if='isAuth("deptAdd")' type="primary" icon="el-icon-plus" @click="addOrUpdateVisible = true">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="detailsBox" ref="tableBox">
        <ag-grid-vue
          class="ag-theme-alpine ag-theme-quartz"
          :gridOptions="gridOptions"
          :localeText="localeText"
          @grid-ready="onGridReady"
          @selection-changed="getSelectedRows"
          @sort-changed="onSortChangedAggrid"
          @filter-changed="onFilterChangedAggrid"
          :rowHeight="38"
          :headerHeight="42"
          :columnDefs="columnDefs"
          :defaultColDef="defaultColDef"
          :rowData="rowData"
          rowSelection="multiple"
          :rowMultiSelectWithClick="true"
          :enableRangeSelection="true"
        >
        </ag-grid-vue>
      </div>
      <div class="pageBox">
        <div>
          选择 <strong style="color: #00b99e;">{{ dataSelect.length }}</strong> 数据
        </div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="page.pageSizes"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        >
        </el-pagination>
      </div>
    </div>



    <el-dialog width='460px' :title="!addOrUpdateForm.id ? '新增' : '修改'" :close-on-click-modal="false" :lock-scroll="false"
      :visible.sync="addOrUpdateVisible" :before-close="closeHandle">
      <el-form inline :model="addOrUpdateForm" :rules="addOrUpdateFormRule" ref="addOrUpdateForm"
        @keyup.enter.native="dataFormSubmit()" label-width="80px">
        <el-form-item label="科室" prop="deptName">
          <el-input v-model.trim="addOrUpdateForm.deptName" placeholder="请填写科室" clearable style='width: 300px'></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeHandle">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import listBtn from '@/views/modules/exercises/deptBtn.vue'
import listJson from '@/views/modules/exercises/dept.json'
import { fetchList } from '@/api/dept.js'
export default {
  beforeMount () {
    this.gridOptions = {
      // 通过这个属性建立了上下文引用
      context: { componentParent: this }
      // 说人话就是可以在自己声明的组件里调用到父组件的方法和属性了
    }
  },
  components: {
    listBtn
  },
  watch: {
    $route: {
      handler (newValue, oldValue) {
        if (oldValue.name === 'exercises-dept') {
          this.addOrUpdateVisible = false
        }
      },
      deep: true
    }
  },
  data () {
    return {
      gridOptions: null,
      localeText: this.$AG_GRID_LOCALE_ZZZ,
      col: [],
      page: {
        pageSizes: [100, 2000, 5000],
        currentPage: 1,
        total: 0,
        pageSize: 100
      },
      searchForm: {
        examPool: ''
      },
      defaultColDef: {
        editable: false,
        sortable: true,
        resizable: true,
        filter: true,
        cellDataType: false
      },
      rowIndexArr: [
        {
          field: 'rowIndex',
          headerName: '序号',
          width: 100,
          checkboxSelection: true,
          headerCheckboxSelection: true,
          sortable: false,
          pinned: 'left',
          valueGetter: (params) => {
            // 返回当前行的序号
            return params.node.rowIndex + 1
          }
        },
        {
          field: 'handle',
          headerName: '操作',
          width: 140,
          pinned: 'right',
          cellRenderer: 'listBtn'
        }
      ],
      columnDefs: [],
      gridApi: null,
      rowData: [],
      dataSelect: [],
      // 带随访数目
      addOrUpdateVisible: false,
      dataList: [],
      tableHeight: 0,
      addOrUpdateForm: {
        deptName: '',
        id: ''
      },
      addOrUpdateFormRule: {
        deptName: [
          {
            required: true,
            message: '科室不能为空',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  created () {
    setTimeout(() => {
      this.tableHeight = this.$refs.tableBox.scrollHeight
      this.getHeadersCol()
      setTimeout(() => {
        this.getList()
      }, 10)
    }, 100)
  },
  methods: {
    onSortChangedAggrid (event) {
      const api = event.api
      const visibleRowCount = api.getDisplayedRowCount()
      for (let i = 0; i < visibleRowCount; i++) {
        const rowNode = api.getDisplayedRowAtIndex(i)
        console.log(rowNode)
      }
      let aaa = JSON.parse(JSON.stringify(this.rowData))
      if (this.gridApi.getRenderedNodes().length > 1) {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
      } else {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
      }
      setTimeout(() => {
        this.rowData = JSON.parse(JSON.stringify(aaa))
        setTimeout(() => {
          if (this.aggridScrollNum !== 0) {
            this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
          }
        }, 10)
      }, 10)
    },
    onFilterChangedAggrid (event) {
      const api = event.api
      const visibleRowCount = api.getDisplayedRowCount()
      for (let i = 0; i < visibleRowCount; i++) {
        const rowNode = api.getDisplayedRowAtIndex(i)
        console.log(rowNode)
      }
      let aaa = JSON.parse(JSON.stringify(this.rowData))
      if (this.gridApi.getRenderedNodes().length > 1) {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[1].rowIndex - 1
      } else {
        this.aggridScrollNum = this.gridApi.getRenderedNodes()[0].rowIndex
      }
      setTimeout(() => {
        this.rowData = JSON.parse(JSON.stringify(aaa))
        setTimeout(() => {
          if (this.aggridScrollNum !== 0) {
            this.gridApi.ensureIndexVisible(this.aggridScrollNum, 'top')
          }
        }, 10)
      }, 10)
    },
    // 获取选中
    getSelectedRows () {
      this.dataSelect = this.gridApi.getSelectedRows()
    },
    // 获取表头
    getHeadersCol () {
      this.columnDefs = []
      setTimeout(() => {
        this.col = JSON.parse(JSON.stringify(listJson.column))
        this.columnDefs = this.rowIndexArr.concat(this.col)
      }, 10)
    },
    // 装载列表
    onGridReady (params) {
      this.gridApi = params.api
    },
    getList () {
      let params = {
        limit: this.page.pageSize,
        page: this.page.currentPage,
        examPool: this.searchForm.examPool || '',
        orderSql: 'creat_date desc'
        // orderSql: 'station_number asc'
      }
      fetchList(params).then(res => {
        console.log('resresresres', res)
        this.rowData = res.data.page.records
        this.page.total = res.data.page.total
        this.dataSelect = []
      })
    },
    handleSizeChange (val) {
      this.page.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.page.currentPage = val
      this.getList()
    },
    // 清空搜索
    searchReset () {
      this.searchForm = {}
      this.page.currentPage = 1
      // this.getList();
    },
    // 每页数
    sizeChangeHandle (val) {
      this.page.pageSize = val
      this.page.currentPage = 1
      this.getList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.page.currentPage = val
      this.getList()
    },

    clearHandle () {
      this.searchForm = {}
      this.page.currentPage = 1
      this.getList()
    },
    closeHandle () {
      this.$refs.addOrUpdateForm.resetFields()
      setTimeout(() => {
        this.addOrUpdateVisible = false
      }, 10)
    },
    dataFormSubmit () {
      this.$refs.addOrUpdateForm.validate(valid => {
        if (valid) {
          if (this.addOrUpdateForm.id) {
            // 编辑
            this.$http({
              url: '/exam/dept/update',
              method: 'post',
              data: {
                id: this.addOrUpdateForm.id,
                deptName: this.addOrUpdateForm.deptName,
                createUserId: this.$store.state.user.id
              }
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.closeHandle()
                this.$message.success('科室编辑成功！')
                this.getList()
              }
            })
          } else {
            this.$http({
              url: '/exam/dept/save',
              method: 'post',
              data: {
                deptName: this.addOrUpdateForm.deptName,
                createUserId: this.$store.state.user.id
              }
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.closeHandle()
                this.$message.success('科室保存成功！')
                this.getList()
              }
            })
          }
        }
      })
    },
    delItem (val) {
      const h = this.$createElement
      this.$msgbox({
        title: '消息',
        message: h('p', { style: 'display: flex;' }, [
          h('i', { class: 'el-icon-delete', style: 'font-size: 22px;color: #ff1744;font-weight: 600;margin-right: 4px' }, ' '),
          h('span', {}, `请确认是否删除科室: ${val.deptName}`)
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '操作中...'
            this.$http({
              url: '/exam/dept/delete',
              method: 'post',
              data: [val.id]
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message.success('科室删除成功！')
                this.getList()
                instance.confirmButtonLoading = false
                done()
              }
            })
          } else {
            instance.confirmButtonLoading = false
            done()
          }
        }
      })
    },
    editItem (val) {
      this.addOrUpdateForm = JSON.parse(JSON.stringify(val))
      this.addOrUpdateVisible = true
    }
  }
}
</script>
<style lang="scss">
.followup-box {
  .inner {
    .table-box {
      flex: 1;
      width: 100%;
    }
  }
}
</style>
